package com;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description: 堆排序
 * User: YJ
 * Date: 2024-4-04
 * Time: 17:01
 */
public class HeapSortExe {

    public static void main(String[] args) {
        int[] arr = new int[]{2, 9, 0, 4, 6, 2, -9};
        HeapSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void HeapSort(int[] array) {
        heapify(array, array.length);
        for (int right = array.length - 1; right > 0; right--) {
            //交换堆顶元素
            swap(array, 0, right);
            //下潜变成大顶堆形式
            recursionDown(array, 0, right);
        }
    }

    /**
     * 建堆
     * 时间复杂度：O(n)
     *
     * @param array
     * @param size
     */
    public static void heapify(int[] array, int size) {
        for (int i = size / 2 - 1; i >= 0; i--) {
            recursionDown(array, i, size);
        }
    }

    /**
     * 堆下潜（递归）
     *
     * @param array
     * @param parent
     * @param size
     */
    public static void recursionDown(int[] array, int parent, int size) {
        int left = parent * 2 + 1;
        int right = left + 1;
        int max = parent;
        if (left < size && array[left] > array[max]) {
            max = left;
        }
        if (right < size && array[right] > array[max]) {
            max = right;
        }
        if (max != parent) {
            //找到了更大的孩子，交换
            swap(array, max, parent);
            //继续判断
            recursionDown(array, max, size);
        }
    }

    /**
     * 堆下潜（非递归）
     * 比递归方式快大约 6 ms
     *
     * @param array
     * @param parent
     * @param size
     */
    public static void nonRecursionDown(int[] array, int parent, int size) {
        while (true) {
            int left = parent * 2 + 1;
            int right = left + 1;
            int max = parent;
            if (left < size && array[left] > array[max]) {
                max = left;
            }
            if (right < size && array[right] > array[max]) {
                max = right;
            }
            if (max == parent) {
                break;
            }
            //找到了更大的孩子，交换
            swap(array, max, parent);
            parent = max;
        }
    }

    /**
     * 交换顺序
     *
     * @param array
     * @param i
     * @param j
     */
    public static void swap(int[] array, int i, int j) {
        int t = array[i];
        array[i] = array[j];
        array[j] = t;
    }
}
